(function(global) {
var APP = global.APP, 
	Spine = global.Spine, 
	$ = global.$;

var Dialog = Spine.Controller.sub();
Dialog.defaults = {
	closeOnEscape : false,
	draggable : false,
	resizable : false,
	width : "auto",
	modal : true
};
Dialog.prototype.init = function() {
	var self = this;

	delete this.options.url;

	this.options = $.extend({}, this.constructor.defaults, this.options);
	if (!this.options.close) {
		this.options.close = function(event) {
			event.preventDefault();
	//		console.log('jquery close');
			self.close(event)
		}
	}
	this.one('open', this.proxy(this.settings));
};
Dialog.prototype.open = function() {
	var url = this.url, content = this.content,
		options = this.options,
		regex = APP._regexScript,
		self = this;
	
	if (this.el.html()) {
		this.el.dialog(options);
		this.trigger('open', this.el);
		return;
	}
	
	$.get(url, function(response) {
		var scripts = response.match(regex) || [];
		// strip out scripts

		response = response.replace(regex, '');
		self.el.append(response)
			.dialog(options);

		// add scripts back
		while (scripts.length) {
			self.el.append(scripts.shift());
		}
		self.trigger('open', self.el);
	});
};
Dialog.prototype.settings = function() {
	var options = this.options;

	if (!options.title) {
		this.el.siblings('.ui-widget-header').removeClass('ui-widget-header');			
	}
	if (!options.scrollable) {
		this.el.css('overflow', 'hidden');
	}
};
Dialog.prototype.close = function(event) {
	if (!event) { 
		this.close = function() {};		// kill close function so it's not called again. prevents triggering twice
	//	console.log('external killed');
		this.el.dialog('close');
		this.trigger('close', true);
		this.destroy();
		return;
	}
//	console.log('internal killed');
	if (event) {
//		console.log('triggering close');
		this.trigger('close');
	}
	this.destroy();
};
Dialog.prototype.destroy = function() {
	var property;
	this.el.dialog('destroy');
	this.release();
	for (property in this) {
		delete this[property];
	}
}

APP.namespace('Modules.Dialog', Dialog);
}) (this);